package basic.Test;

public class CopyTestDeep {
	
	public static void main(String[]args) throws CloneNotSupportedException{
		
	    //teacher对象将被clone出来的Student对象共享.  
        Teacher teacher = new Teacher();  
        teacher.setAge(40);  
        teacher.setName("Teacher zhang");  
          
        StudentDeep student1 = new StudentDeep();  
        student1.setAge(20);  
        student1.setName("zhangsan");  
        student1.setTeacher(teacher);  
          
        //复制出来一个对象student2，但是此時student中的teacher引用指向同一個地方  
        StudentDeep student2 = (StudentDeep)student1.clone();  
        System.out.println(student2.getAge());  
        System.out.println(student2.getName());  
          
          
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~");  
        System.out.println(student1.getTeacher().getAge());  
        System.out.println(student1.getTeacher().getName());  
          
          
        //修改student2的引用对象  
        student2.getTeacher().setAge(50);  
        student2.getTeacher().setName("Teacher Li");  
          
        System.out.println("~~~~~~~~~~~~~~~~~~~~~~");  
        System.out.println(student1.getTeacher().getAge());  
        System.out.println(student1.getTeacher().getName());  
        
	}

}
/*
20
zhangsan
~~~~~~~~~~~~~~~~~~~~~~
40
Teacher zhang
~~~~~~~~~~~~~~~~~~~~~~
40
Teacher zhang
 * */

 
  
class StudentDeep implements Cloneable{  
      
    public int age ;  
    public String name;  
    public Teacher teacher;  
    public int getAge() {  
        return age;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public Teacher getTeacher() {  
        return teacher;  
    }  
    public void setTeacher(Teacher teacher) {  
        this.teacher = teacher;  
    }  
    @Override  
    public Object clone() throws CloneNotSupportedException {  
    	StudentDeep student = (StudentDeep)super.clone();  
         //将引用的对象teacher也clone下  
         student.setTeacher((Teacher)(student.getTeacher().clone()));  
         return student;  
    }  
      
}  